package com.zqweb.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zqweb.common.utils.R;
import com.zqweb.gulimall.product.entity.SkuImagesEntity;
import com.zqweb.gulimall.product.entity.SpuInfoDescEntity;
import com.zqweb.gulimall.product.entity.SpuInfoEntity;
import com.zqweb.gulimall.product.feign.SeckillFeignService;
import com.zqweb.gulimall.product.service.*;
import com.zqweb.gulimall.product.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zqweb.common.utils.PageUtils;
import com.zqweb.common.utils.Query;

import com.zqweb.gulimall.product.dao.SkuInfoDao;
import com.zqweb.gulimall.product.entity.SkuInfoEntity;
import org.springframework.util.StringUtils;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private SeckillFeignService seckillFeignService;
    @Autowired
    private ThreadPoolExecutor threadPool;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    // 带条件参数的过滤分页查询
    public PageUtils queryPageWithConditions(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper) -> {
                wrapper.like("sku_id",key).or().like("sku_name",key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId) && !"0".equals(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);
        }
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && !"0".equals(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }
        String min = (String) params.get("min");
        if(!StringUtils.isEmpty(min)){
            queryWrapper.ge("price",min);
        }
        String max = (String) params.get("max");
        if(!StringUtils.isEmpty(max)){
            // 最大商品价格需要大于0，否则检索无意义
            BigDecimal bigDecimal = new BigDecimal(max);
            if(bigDecimal.compareTo(new BigDecimal("0")) == 1){
                queryWrapper.le("price",max);
            }
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> up(Long spuId) {
        List<SkuInfoEntity> skuInfoEntities = this.baseMapper.selectList(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return skuInfoEntities;
    }

    @Override
    public SkuInfoItemVo getItemDetailsBySkuId(Long skuId) throws ExecutionException, InterruptedException {
        SkuInfoItemVo skuInfoItemVo = new SkuInfoItemVo();
        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            //1、sku基本信息的获取  pms_sku_info
            SkuInfoEntity skuInfoEntity = this.baseMapper.selectById(skuId);
            skuInfoItemVo.setInfo(skuInfoEntity);
            return skuInfoEntity;
        }, threadPool);

        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            //2、sku的图片信息    pms_sku_images
            BaseMapper<SkuImagesEntity> skuImageDao = skuImagesService.getBaseMapper();
            List<SkuImagesEntity> skuImages = skuImageDao.selectList(new QueryWrapper<SkuImagesEntity>().eq("sku_id", skuId));
            skuInfoItemVo.setImages(skuImages);
        }, threadPool);

        CompletableFuture<Void> saleAttrFuture = skuInfoFuture.thenAcceptAsync(skuInfoEntity -> {
            //3、获取spu的销售属性组合
            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSpuAttrsBySpuId(skuInfoEntity.getSpuId());
            skuInfoItemVo.setSaleAttr(saleAttrVos);
        }, threadPool);

        CompletableFuture<Void> descFuture = skuInfoFuture.thenAcceptAsync(skuInfoEntity -> {
            //4、获取spu的介绍
            SpuInfoDescEntity desc = spuInfoDescService.getById(skuInfoEntity.getSpuId());
            skuInfoItemVo.setDesc(desc);
        }, threadPool);

        CompletableFuture<Void> groupAttrsFuture = skuInfoFuture.thenAcceptAsync(skuInfoEntity -> {
        /*
        5、获取spu的规格参数信息
        传入当前spuId和catelogId，查询出指定spuId和指定catelogId下的attrGroup有哪些，而这些attrGroup同样设置好
        相应的attr信息（attrName、attrValue）
         */
            List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithAttrsBySpuIdAndCatelogId(skuInfoEntity.getSpuId(), skuInfoEntity.getCatalogId());
            skuInfoItemVo.setGroupAttrs(attrGroupVos);
        }, threadPool);

        //6、秒杀商品的优惠信息
        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            R r = seckillFeignService.getSeckillSkusInfoBySkuId(skuId);
            if (r != null && r.getCode() == 0) {
                SeckillSkuInfoVo skuInfoVo = r.getData(new TypeReference<SeckillSkuInfoVo>() {
                });
                if (skuInfoVo != null) {
                    skuInfoItemVo.setSeckillSkuInfoVo(skuInfoVo);
                }
            }
        }, threadPool);


        // 在上述所有业务任务执行完毕，skuInfoItemVo赋值完全，才将skuInfoItemVo结果类返回，否则阻塞等待，直到get到相应任务的执行结果
        CompletableFuture.allOf(imageFuture,saleAttrFuture,descFuture,groupAttrsFuture,seckillFuture).get();
        System.out.println(skuInfoItemVo);
        return skuInfoItemVo;
    }


    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }



}